//
//  HomeController.m
//  HarmonizePub
//
//  Created by rzhy on 2016/10/31.
//  Copyright © 2016年 Zy. All rights reserved.
//


#import "HomeController.h"
#import "Config.h"
#import "YYInfiniteLoopView.h"
#import "HomeTableHeadView.h"
#import "HomeTableViewCell.h"
#import "GuidePageView.h"
#import "LoginController.h"
#import "ChoosePatientViewController.h"
#import "WebViewController.h"
#import "CollectionTableCell.h"
#import <JPUSHService.h>

static NSString * CellIdentifier = @"Cell";
static CGFloat const loopViewH = 180.0f;

typedef NS_ENUM(NSUInteger, HomeMenuItemType) {
    HomeMenuItemTypeJump = 0,
    HomeMenuItemTypeChoosePatient = 1,
    HomeMenuItemTypeWebView = 2
};

@interface HomeController () <UITableViewDelegate, UITableViewDataSource, HomeTableViewCellDelegate, LoginControllerDelegate, UIScrollViewDelegate>
{
    UIPageControl   *_page;
    NSArray         *_colorArray;
    NSDictionary    *_menuDataDict;
    NSInteger       _index;
    
    UIScrollView    *_scrollView;
    CGSize          _size;
    NSArray         *_imageNameArray;
    YYInfiniteLoopView *_loopView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation HomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // [self setScrollViewAttr];
    _colorArray = @[RGBColor(60, 177, 255), RGBColor(243, 139, 183), RGBColor(254, 245, 92), RGBColor(15, 205, 110)];
    _menuDataDict = [self getData];
    UINib *nib = [UINib nibWithNibName:[HomeTableViewCell registerName] bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"CollectionTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CollectionTableCell"];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(skipLogin) name:@"XHLogin" object:nil];
    [self getScrollImage];
}


- (NSDictionary *)getData {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HomeMenuData" ofType:@"plist"];
    NSDictionary *rootDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSString *key = @"CFBundleShortVersionString";
    NSString *saveVersion = [UserDefaultsTool stringForKey:key];
    BOOL b = [UserDefaultsTool boolForKey:XHIsDebug];
    if (b || saveVersion == nil) {
        NSMutableDictionary *dictM = [rootDict mutableCopy];
        NSMutableArray *menuArray = [rootDict[@"Menu"] mutableCopy];
        NSMutableArray *listArray = [NSMutableArray arrayWithCapacity:menuArray.count];
        for (NSArray *array in menuArray) {
            NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
            for (NSDictionary *dict in array) {
                NSString *title = dict[@"title"];
                if (
                    ![title isEqualToString:@"门诊结算"]) {
                    [arrayM addObject:dict];
                }
            }
            [listArray addObject:arrayM];
        }
        [dictM setValue:listArray forKey:@"Menu"];
        [self performSelector:@selector(reloadTableData) withObject:nil afterDelay:1.5f];
         return [dictM copy];
    }
    return rootDict;
}

- (void)reloadTableData {
    _menuDataDict = [self getData];
    [self.tableView reloadData];
}

#pragma mark - login event
- (void)skipLogin {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"登录超时,请重新登录!" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [JPUSHService setTags:nil alias:@"" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//            XHLog(@"超时清空别名 -> iResCode: %d, iTags: %@, iAlias: %@", iResCode, iTags, iAlias);
        }];
        LoginController *login = [[LoginController alloc] init];
        login.delegate = weakSelf;
        [weakSelf.currentViewController presentViewController:login animated:YES completion:nil];
    }];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)cancelLogin:(LoginController *)login {
    UITabBarItem *item = self.tabBarController.tabBar.items[0];
    [self.tabBarController tabBar:self.tabBarController.tabBar didSelectItem:item];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_menuDataDict[@"Head"] count] + 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section) {
//        NSArray *array = _menuDataDict[@"Menu"];
//        NSArray *itemArray = array[indexPath.section - 1];
//        return [HomeTableViewCell cellHeightWithDataArray:itemArray];
//    }
//    return loopViewH;
    if (indexPath.section == 0) {
        return  loopViewH;
    }else if (indexPath.section == 1){
        return  loopViewH;
    }else{
        NSArray *array = _menuDataDict[@"Menu"];
        NSArray *itemArray = array[indexPath.section -2 ];
        return [HomeTableViewCell cellHeightWithDataArray:itemArray];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//
//    if (indexPath.section == 0) {
//        cell = [tableView dequeueReusableCellWithIdentifier:@"ScrollViewCell"];
//        if (!cell)
//            cell = (HomeTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ScrollViewCell"];
//        [cell addSubview:[self createLoopView]];
//    } else {
//        cell.delegate = self;
//        cell.dataArray = _menuDataDict[@"Menu"][indexPath.section - 1];
//    }
//
//    return cell;
    
    
    if (indexPath.section == 0) {
         HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell = [tableView dequeueReusableCellWithIdentifier:@"ScrollViewCell"];
        if (!cell)
            cell = (HomeTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ScrollViewCell"];
        [cell addSubview:[self createLoopView]];
        return cell;
    }else if (indexPath.section ==1){
        CollectionTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectionTableCell"];
        cell.previousVC = self;
        return cell;
    } else {
         HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.delegate = self;
        cell.dataArray = _menuDataDict[@"Menu"][indexPath.section - 2];
        return cell;
    }
    
    return [[UITableViewCell alloc]init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    if (section)
//        return [HomeTableHeadView height];
//    return 0.01f;
    if (section == 0){
        return 0.01;
    }else{
        return [HomeTableHeadView height];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if (section == [_menuDataDict[@"Head"] count] || section == 0) return 0.01f;
//    return 8.0f;
    if ( section == 0){
        return 0.01f;
    }else{
        return 8.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    if (section) {
//        HomeTableHeadView *headView = [HomeTableHeadView headView];
//        headView.view.backgroundColor = _colorArray[section - 1];
//        headView.titleLabel.text = _menuDataDict[@"Head"][section - 1];
//        return headView;
//    }
//    return nil;
    if (section==0) {
        return nil;
    }else if (section ==1){
        HomeTableHeadView *headView = [HomeTableHeadView headView];
        headView.view.backgroundColor = [UIColor colorWithRed:36/255.f green:82/255.f blue:153/255.f alpha:1];
        headView.titleLabel.text = @"医健通";
        return headView;
    }else{
        HomeTableHeadView *headView = [HomeTableHeadView headView];
        headView.view.backgroundColor = _colorArray[section - 2];
        headView.titleLabel.text = _menuDataDict[@"Head"][section - 2];
        return headView;
    }
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (void)tableViewCell:(HomeTableViewCell *)tableViewCell didSelectedItemAtDataDictionary:(NSDictionary *)dataDict {
    HomeMenuItemType type = [dataDict[@"type"] integerValue];
    NSString *title = dataDict[@"title"];
    NSString *string = [dataDict[@"string"] isEqualToString:@""] ? nil : dataDict[@"string"];
    NSInteger medicaltype = [dataDict[@"MedicalType"] integerValue];
//    NSLog(@"=======%@",string);
    if (string.length) {
        switch (type) {
            case HomeMenuItemTypeJump: {
                // 0: 跳转
                if ([title isEqualToString:@"医院导航"])
                    if ([UserDefaultsTool boolForKey:XHIsDebug]) {
//                        [self setAlertViewWithMessage:XHAlertMsg];
//                        return ; 
                    }
                UIViewController *viewController = [[NSClassFromString(string) alloc] init];
                viewController.title = title;
                [self.navigationController pushViewController:viewController animated:YES];
                break;
            }
            case HomeMenuItemTypeChoosePatient: {
                // 1: 选择就诊人
                [ChoosePatientViewController patientWithCurrentController:self nextController:string patientListType:medicaltype];
                break;
            }       
            case HomeMenuItemTypeWebView:{
                // 2: webView
                WebViewController *webView = [[WebViewController alloc] init];
                webView.title = title;
                webView.url = [URLTool webURLStringWithPathString:string token:[UserDefaultsTool stringForKey:XHToken]];
                [self.navigationController pushViewController:webView animated:YES];
                break;
            }
        }
    } else {
        [self setAlertViewWithMessage:XHAlertMsg];
    }
}

#pragma mark - create Loop View
- (UIView *)createLoopView {
    if (_loopView) return _loopView;
    NSArray *imageArray = @[@"轮播图首页", @"轮播图首页", @"轮播图首页"];
    __weak typeof(self) weakSelf = self;
    _loopView = [YYInfiniteLoopView infiniteLoopViewWithImageUrls:imageArray titles:nil didSelectedImage:^(NSInteger index) {
        [weakSelf touchLoopViewEventWithIndex:index];
    }];
    _loopView.placeholderImage = [UIImage imageNamed:@"轮播图首页"];
    _loopView.currentPageIndicatorColor = [UIColor whiteColor];
    _loopView.pageIndicatorColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    _loopView.bgViewColor = [[UIColor blackColor] colorWithAlphaComponent:0.3f];
    _loopView.frame = (CGRect){CGPointZero, XHScreenWidth, loopViewH};
    return _loopView;
}

#pragma mark touch loopView event
- (void)touchLoopViewEventWithIndex:(NSInteger)index {
    NSString *title = _loopView.titles[index];
    // TODO: Touch Loop View
    XHLog(@"title: %@", title);
}

#pragma mark - scrollImage
- (void)getScrollImage {
    NSString *urlString = [NSString stringWithFormat:@"%@", XHHomeScrollImagePath];
    NSDictionary *param = @{@"type" : XHType};
//    XHLog(@"首页轮播图: path: %@\n\t参数: %@", urlString, param)
    __unsafe_unretained HomeController *weakSelf = self;
    [HTTPSTool GETRequestHidenHUDWithPath:urlString cookie:nil params:param progress:nil success:^(NSDictionary * JSON) {
        XHLog(@"首页轮播图 -> JSON: %@", JSON)
        [weakSelf setScrollImageWithDataArray:JSON[@"data"][@"list"]];
    } failure:nil];
}

- (void)setScrollImageWithDataArray:(NSArray *)dataArray {
    if (!dataArray.count) return ;
    // 轮播图处理
    NSMutableArray *imageArrayM = [NSMutableArray arrayWithCapacity:dataArray.count];
    NSMutableArray *titleArrayM = [NSMutableArray arrayWithCapacity:dataArray.count];
    for (NSDictionary *dataDict in dataArray) {
        NSURL *imageUrl = [URLTool imageURLStringWithPathString:dataDict[@"image"]];
        [imageArrayM addObject:[imageUrl absoluteString]];
        [titleArrayM addObject:dataDict[@"title"]];
    }
    _loopView.titles = titleArrayM;
    _loopView.imageUrls = imageArrayM;
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - GuidePage
- (void)setScrollViewAttr {
    NSString *key = @"CFBundleShortVersionString";
    NSString *version = [NSBundle mainBundle].infoDictionary[key];
    NSString *saveVersion = [UserDefaultsTool stringForKey:key];
    if ([version isEqualToString:saveVersion]) {
        [self getScrollImage];
    } else {
        __weak typeof(self) weakSelf = self;
        GuidePageView *view = [GuidePageView guidePageViewComplete:^(GuidePageView *guidePageView) {
            [weakSelf getScrollImage];
            NSString *key = @"CFBundleShortVersionString";
            NSString *version = [NSBundle mainBundle].infoDictionary[key];
            [UserDefaultsTool setObject:version forKey:key];
        }];
        view.plistFile = @"GuidePageData.plist";
        view.showPage = YES;
    }
}

@end
